'use strict';

const BaseController = require('../base');
const {
  registerValidate,
  loginValidate,
  userDetailValidate,
  userEditValidate,
} = require('@validators/users');

class UsersController extends BaseController {
  /**
   * 生成token
   */
  async generateToken({ id, username }) {
    const { app } = this;
    const token = app.jwt.sign(
      {
        username,
        id,
      },
      app.config.jwt.secret,
      {
        expiresIn: app.config.expiresIn,
      }
    );

    await app.redis.set(username, token, 'EX', app.config.expiresIn);
    return token;
  }

  parseResult(ctx, result) {
    return {
      id: result.getDataValue('id'),
      username: result.getDataValue('username'),
      signTime: ctx.helper.timestamp(result.getDataValue('signTime')),
    };
  }
  /**
   * 注册
   */
  async register() {
    const { ctx } = this;
    const v = await registerValidate(ctx);
    const result = await ctx.service.users.addUser({
      username: v.get('body.username'),
      password: v.get('body.password2'),
    });
    const token = await this.generateToken({
      id: result.id,
      username: result.username,
    });
    this.success({ ...this.parseResult(ctx, result), token });
  }
  /**
   * 登录
   */
  async login() {
    const { ctx } = this;
    const v = await loginValidate(ctx);
    const token = await this.generateToken({
      id: v.id,
      username: v.username,
    });
    this.success({ ...this.parseResult(ctx, v), token });
  }

  async edit() {
    const { ctx } = this;
    const v = await userEditValidate(ctx);
    const result = await ctx.service.users.editUser({
      avatar: v.get('body.avatar'),
      phone: v.get('body.phone'),
      sign: ctx.helper.escape(v.get('body.sign')),
    });
    result && ctx.helper.success();
  }

  /**
   * 获取用户信息
   */
  async detail() {
    const { ctx } = this;
    const result = await userDetailValidate(ctx);
    const { signTime, updateTime, ...rest } = result.dataValues;
    this.success(
      ctx.helper.unPick(
        {
          ...rest,
          signTime: ctx.helper.timestamp(signTime),
          updateTime: ctx.helper.timestamp(updateTime),
        },
        'dataValues.password'
      )
    );
  }

  async logout() {
    const { ctx, app } = this;
    await app.redis.del(ctx.username);
    ctx.helper.success();
  }
}

module.exports = UsersController;
